import Vue from 'vue'
// import { Alert } from 'vux'

import fixBottom from '@/components/fixBottom'
// import XButton from 'vux/src/components/x-button/index.vue'
import { Button, ButtonGroup } from 'vue-ydui/dist/lib.px/button'
// import Confirm from 'vux/src/components/confirm/index.vue'
import { Toast } from 'vue-ydui/dist/lib.px/dialog'
import { Popup } from 'vue-ydui/dist/lib.rem/popup';

// Vue.component(Loadmore.name, Loadmore);
Vue.component(Popup.name, Popup);
Vue.component(Button.name, Button)
Vue.component(ButtonGroup.name, ButtonGroup)

export default {
  name: 'shopCar',
  data() {
    return {
      checkAll: false,
      totalMoney: 0,
      delFlag: false,
      curDel: '',
      editFlag: false,
      toDelect: false,
      containerId:'',//货架id
      companyId:'', //公司id
      valueId:'',//商品id
      // goodNumber:0,
      shopData: [
      ]
      // shopNoneFlag:boolean
    }
  },
  components: {
    fixBottom,
    // XButton,
    // Confirm
  },
  created: function () {
    // localStorage.setItem('item1', item1)
    this.getGoods()
    
  },

  beforeDestroy: function () {
    if (!window.localStorage) {
      alert("浏览器不支持localstorage");
      return false;
    } else {
      // var localStorage = window.localStorage;
      // var _this = this;
      for (var i = 0; i < localStorage.length; i++) {
        let key = localStorage.key(i);
        if (key.match(/^item[0-9]+$/)) {
          let valueId = localStorage.getItem(key).split(',')[0]; //获取商品id
          // let valueSize = localStorage.getItem(key).split(',')[2]; //商品规格
          this.shopData.forEach(function (value, index) {
            if ((value.productId + '') == valueId) {
              if (localStorage.getItem(key).split(',')[1] != value.quentity) {
                //判断商品数量是否发生变化
                localStorage.setItem(key, value.productId + ',' + value.quentity);
              }
            }
          });
        }
      }
    }
  },

  computed: {

    shopNoneFlag: function () {
      if (this.shopData.length == 0) {
        return true;
      } else {
        return false
      }
    },
    // 点击修改购买商品数量
    checkNum: function () {
      var num = 0;
      this.shopData.forEach( (item, index) =>{
        if (item.checked) {
          num = num + parseInt(item.quentity);
        }
      });
      return num;
    }
  },

  methods: {
  // 获取商品
    getGoods () {
    for (var i = 0; i < localStorage.length; i++) {
      let key = localStorage.key(i);
      console.log(key)
      if (key.match(/^item[0-9]+$/)) { // 判断存的是否是商品item[i]
        this.valueId = localStorage.getItem(key).split(',')[0]; //获取商品id
        var quentity = localStorage.getItem(key).split(',')[1]  //获取商品的购买数量
       this.containerId = localStorage.getItem(key).split(',')[2]  //获取商品的货架id
       var lid = localStorage.getItem('lid') //获取商品的货架层id
       var price = localStorage.getItem('price') //获取商品的价格
        // console.log( price )
        this.axios.post('/goods/down/order', {
          params: {
            openid:sessionStorage.getItem('openid'),
            price:this.totalMoney,
            goods_info:[{
              cid:1,//公司id
              sid:this.containerId, //货架id
              lid:lid,//货架的层id
              gid:this.valueId,//商品id
              amount:quentity,//商品数量
            }]
          }
        }).then(res=> {
          console.log(res)
        var shopProduct = {};
        // shopProduct.id = res.data.datas.id; //商品id
        // shopProduct.name = res.data.datas.name; //商品名字
        // shopProduct.productPic = res.data.datas.thumb; //商品图片
        // shopProduct.quentity = localStorage.getItem(key).split(',')[1]; //商品数量
        // shopProduct.curPrice = res.data.datas.price; //商品价格
        // this.shopData.push(shopProduct);

        shopProduct.id=i
        shopProduct.name='商品'+i
        shopProduct.curPrice = price
        shopProduct.quentity = localStorage.getItem(key).split(',')[1]; //商品数量
        this.shopData.push(shopProduct);
        // console.log('shopData',this.shopData)
        }, err=> {
          // console.log(err);
        })
      }
    }
    },
    onCancel() {
      this.delFlag = false
    },
    // 跳转到商品详情
    goToDetails: function (id) {
      // this.$router.push("/details?id=" + id);
    },
    //结算
    goToSettlement: function () {
      // 跳转到购买页面
      var _this = this;
      if (this.checkNum != 0) {
        // // 微信授权
        // if (process.env.NODE_ENV == 'development') { //开发环境
        //     // this.$store.commit('getOpenid','ou0Ez1MhlFFdR12Bvs72bnYxQoWE')
        //     this.$store.state.user.openid = 'ou0Ez1MhlFFdR12Bvs72bnYxQoWE'
        // } else { //上线环境
        //     if (this.$route.query.openid != undefined) {
        //         // this.$store.commit('getOpenid',this.$route.query.openid)
        //         this.$store.state.user.openid = 'ou0Ez1MhlFFdR12Bvs72bnYxQoWE'
        //     } 
        //     if(this.$store.state.user.openid){
        //         // next();
        //     }else{
        //         var redirect_uri = this.axios.defaults.baseURL + "/wechat/redirect/url?page=http://sljsp.anasit.com" + this.$route.fullPath
        //         // var redirect_uri = "http%3a%2f%2fsljspapi.anasit.com%2fwechat%2fredirect%2furl%3fpage%3dhttp%3a%2f%2fsljsp.anasit.com%2fmy"
        //         window.location.href="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxb2cc0a549df3882c&redirect_uri="+encodeURIComponent(redirect_uri)+"&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect"
        //     }
        // } 
        var temp = [];
        // var _this = this;
        for (var i = 0; i < this.shopData.length; i++) {
          // console.log("shopdata",this.shopData[0].count)
          if (this.shopData[i].checked) {
            if (this.shopData[i].quentity <= parseInt(this.shopData[i].number)) {
              temp.push({
                "id": parseInt(this.shopData[i].productId),
                "amount": parseInt(this.shopData[i].quentity),
              });
            } 
            // else {
            //   Toast({
            //     mes: this.shopData[i].productName + '库存不足',
            //     timeout: 1000
            //   });
            //   return;
            // }
          }
        }
        var _price = this.totalMoney + '';
        var tempToJson = JSON.stringify(temp);
        // var tempToJson = temp;
        // this.$router.push('/settlement')
        // _this.$router.push('/settlement?from=shop');
        _this.$router.push('/settlement?from=shop&temp=' + tempToJson);
        // this.axios.post("/order/tmporder", {
        //     "price": _price,
        //     "fee": 0,
        //     "goods": tempToJson,
        //     "openid": sessionStorage.getItem('openid')
        // }).then(function(res) {
        //     if (res.data.result) {
        //         _this.$router.push('/settlement?from=shop&ordersn=' + res.data.datas.ordersn);
        //     } else {
        //         Toast({
        //             mes: res.data.message
        //         });
        //     }
        // }, function(err) {
        //     console.log(err.data);
        // })
      } else {
        //未选择结算项目
        Toast({
          mes: '请选择结算项目',
          timeout: 1000
        });
      }
    },
    // 修改购买商品数量
    changeQuentity: function (item, num) {
      console.log("item", item)
      var localStorage = window.localStorage;
      var i = 1;
      if (num > 0) {
        // if (parseInt(item.quentity) < parseInt(item.count)) {
        item.quentity++;
        localStorage.setItem('item' + i, item.id + ',' + item.quentity + ',' + containerId);
        // } else {
        //   // Toast({
        //   //   mes: '库存不足',
        //   //   timeout: 1000
        //   // });
        // }
      } else {
        if (item.quentity > 1) {
          item.quentity--;
          localStorage.setItem('item' + i, item.id + ',' + item.quentity + ',' + item.containerId);
        }
      }
      this.calctotalMoney();
    },
    // 选择
    selectProduct: function (item) { 
      var flag = true;
      if (typeof item.checked == 'undefined') {
        this.$set(item, 'checked', true)
      } else {
        item.checked = !item.checked;
      }
      this.shopData.forEach(function (item, index) {
        if (!item.checked) {
          flag = false;
        }
      });
      this.checkAll = flag;
      // console.log('选择之后', item)
      this.calctotalMoney();
    },
    // 全选
    checkAllProduct: function () {
      this.checkAll = !this.checkAll;
      var _this = this;
      this.shopData.forEach(function (item, index) {
        if (typeof item.checked == 'undefined') {
          _this.$set(item, 'checked', true)
        } else {
          if (_this.checkAll) {
            item.checked = true;
          } else {
            item.checked = false;
          }
        }
      });
      this.calctotalMoney();
    },
    //计算总金额
    calctotalMoney: function () {
      this.shopData.forEach((item, index) => {
        // if (item.checked) {
          // console.log(parseInt(item.quentity))
          this.totalMoney = parseInt(this.checkNum) * parseFloat(item.curPrice)
          console.log(this.totalMoney)
        // }
        
      });
    },
    // 删除数据
    // confirmDel: function (item) {
    //   console.log('123')
    //   this.delFlag = true;
    //   this.curDel = item;
    // },
    confirmDel: function (item) {
      console.log('item',item)
      if (this.checkNum == 0) {
          Toast({
            mes: '请至少选择一项商品',
            timeout: 1000
          });
          return
      } 
      this.shopData.forEach( (value, index) => {
        if (value.checked) {
          //删除localstorage中的数据
          for (var i = 0; i < localStorage.length; i++) {
            let key = localStorage.key(i);
            if (key.match(/^item[0-9]+$/)) {
              console.log('key',key)
              let valueId = localStorage.getItem(key).split(',')[0]; //获取商品id
              if (valueId == (value.id + '')) {
                console.log('if')
                //判断是否是当前要删除的数据
                localStorage.removeItem(key);
                  // let pageIndex = this.shopData.indexOf();
                  // console.log('pageIndex', pageIndex)
                  // this.shopData.splice(pageIndex, 1);
                  // this.calctotalMoney();
              } else {
                console.log('else valueId', valueId)
              }
            }
          }
          
        }
        
      });
      
      // //删除显示数据      
      // this.shopData.forEach(function (value, index) {
      //   console.log('value',value)
      //   let pageIndex = this.shopData.indexOf(shopItem);
      //   console.log('pageIndex', pageIndex)
      //   this.calctotalMoney();
      // })   
      // this.getGoods()       
      
    }
  },
  filters: {
    formatMoney: function (value) {
      if (typeof value == "number") {
        return "￥" + value.toFixed(2);
      }
    }
  },
  mounted(){
    // this.getGoods()
  }
}
